#include "LspSupport.h"

#include "simodo/shell/access/LspAccess_interface.h"
#include "simodo/lsp-client/SimodoCapabilities.h"

#include <QFileInfo>
#include <QComboBox>

#include <fstream>
#include <chrono>

LspSupport::LspSupport(shell::Runner_plugin * plugin, shell::Access_interface & shell)
    : _plugin(plugin)
    , _shell(shell)
{
    _run_management = _shell.getRunnerManagement();

    connect(this, &LspSupport::notification_received_signal, this, &LspSupport::notification_received_slot);
    connect(this, &LspSupport::ran_signal, this, &LspSupport::ran_slot);
    connect(this, &LspSupport::paused_signal, this, &LspSupport::paused_slot);
    connect(this, &LspSupport::stoped_signal, this, &LspSupport::stoped_slot);

    _combo = new QComboBox();
    _combo->setEnabled(false);
    _combo->setFocusPolicy(Qt::FocusPolicy::NoFocus);
    _combo->setToolTip(tr("Command name"));
    _combo->setStatusTip(tr("Choosing a command"));
    _combo->setMinimumWidth(120);
}

QString LspSupport::name() const
{
    return tr("SIMODO LSP+");
}

QString LspSupport::description() const
{
    return tr("SIMODO LSP+ support");
}

bool LspSupport::isRunnable(const QString & path) 
{
    _last_path = path;
    shell::LspAccess_interface * lsp = _shell.getLspAccess(path);

    if (!lsp)
        return false;

    simodo::lsp::SimodoCapabilities cap = lsp->getSimodoCapabilities(path);

    if (!cap.runnerProvider)
        return false;

    for(const simodo::lsp::SimodoRunnerOption & opt : cap.runnerOptions)
        if (lsp->getLanguageId(_last_path) == opt.languageID)
            return true;

    return false;
}

bool LspSupport::startModeling(const QString & path) 
{
    _error_text = "";

    shell::LspAccess_interface * lsp = _shell.getLspAccess(path);

    if (!lsp)
        return false;

    lsp->executeSimodoCommand(path, _combo->currentText());
    return true;
}

bool LspSupport::pauseModeling() 
{
    return false;
}

bool LspSupport::stopModeling() 
{
    return false;
}

QWidget *LspSupport::getToolbarWidget()
{
    _combo->clear();

    shell::LspAccess_interface * lsp = _shell.getLspAccess(_last_path);

    if (!lsp)
        return nullptr;

    simodo::lsp::SimodoCapabilities cap = lsp->getSimodoCapabilities(_last_path);

    for(const simodo::lsp::SimodoRunnerOption & opt : cap.runnerOptions)
        if (lsp->getLanguageId(_last_path) == opt.languageID)
            _combo->addItem(QString::fromStdU16String(opt.viewName));

    if (_combo->count() > 0)
        _combo->setEnabled(true);

    return _combo;
}

void LspSupport::notification_received_slot(const QString text)
{
    if (_run_management)
        _run_management->received(text);
}

void LspSupport::ran_slot()
{
    if (_run_management)
        _run_management->started();
}

void LspSupport::paused_slot()
{
    if (_run_management)
        _run_management->paused();
}

void LspSupport::stoped_slot()
{
    if (_run_management)
        _run_management->stoped();
}

